<?php
/*********************************************************************************
easyZenImport v.8b - Easy, Ajax Driven Importing Front-End For EasyPopulate 
Copyright (C) 11-02-06 Nick Van Dorsten
Author: Nick Van Dorsten <nickvd@gmail.com>

This library is free software; you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2.1 of the License, or (at your option) any later
version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.

You should have received a copy of the GNU Lesser General Public License along
with this library; if not, write to the Free Software Foundation, Inc., 
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
*********************************************************************************/
function goodnl2br($input){return preg_replace("/(\r?\n)+/","<br/>",$input);}

function getCategoryTree($parent_id = '0', $spacing = '', $exclude = '', $category_tree_array = '', $include_itself = false, $limit = false) {
   global $db;
   if ($limit) {$limit_count = " limit 1";}
   else {$limit_count = '';}
   if (!is_array($category_tree_array)) $category_tree_array = array();
   if ($include_itself) {
      $category = $db->Execute("select cd.categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " cd where cd.categories_id = '" . (int)$parent_id . "'");
      $category_tree_array[] = array('id' => $parent_id, 'text' => $category->fields['categories_name']);
   }
   $categories = $db->Execute("select c.categories_id, cd.categories_name, c.parent_id from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id and c.parent_id = '" . (int)$parent_id . "' order by c.sort_order, cd.categories_name");
   while (!$categories->EOF) {
      $mark = '&nbsp;&nbsp;';
      if ($exclude != $categories->fields['categories_id']) $category_tree_array[] = array('id' => $categories->fields['categories_id'], 'text' => $spacing . $categories->fields['categories_name'] . $mark);
      $category_tree_array = @getCategoryTree($categories->fields['categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $category_tree_array, '');
      $categories->MoveNext();
   }
   return $category_tree_array;
}

function getCatOptions(){
   $tree = @getCategoryTree();
   $catOptions = '';
//   trap($tree);
  // die();
   
   foreach ($tree as $val) {
      $value = str_replace("&nbsp;","",$val['text']);
      $catOptions .= "<option value='{$value}'>{$val['text']}</option>";
   }
   return $catOptions;
}

function readQueueFile($file='queue.csv') {
   $fileArr = false;
   if (file_exists(ZENCART_PATH.'temp/'.$file)) {
      $cFile = file(ZENCART_PATH.'temp/'.$file);
      foreach ($cFile as $row) {
         $rowArr = explode("\t",rtrim($row));
         $fileArr[] = $rowArr;
      }
   }
   return $fileArr;
}

function formatQueue($q=null) {
   if (is_null($q)) die('NO Q PASSED');
   global $PKI;
   $out = '';
   array_shift($q);
   foreach ($q as $i => $queue) {
      $name = $queue[$PKI['PRODUCTS_NAME']];
      $price = $queue[$PKI['PRODUCTS_PRICE']];
      $cat = $queue[$PKI['CATEGORIES_NAME_1']];
      $image = "<img src='".DIR_WS_CATALOG_IMAGES."thumb/{$queue[$PKI['PRODUCTS_IMAGE']]}' alt=''/>";
      $out .= "<div id='queue_".($i+1)."'>{$image}<a href='eazyImport.php?act=d&amp;i=".($i+1)."' class='btnDelete'><img src='images/editdelete.png' alt='Remove'/></a><span class='queuePrice'>\$ {$price}</span><span class='queueName'>{$name}</span><br/><span class='queueCat'>{$cat}</span></div>";
   }
   return $out;
}

function formatProductArray($input,$date=null) {
   global $PKM;

   if(is_int($date)) $date = date('Y-m-d H:i:s',$date);
   elseif (!@strtotime($date)) $date = date('Y-m-d H:i:s');

   if (!empty($_FILES)) {
      $imageFilename = doImageUpload();
   } else $imageFilename = '';

   foreach ($PKM as $val) {
      switch ($val) {
         case 'PRODUCTS_MODEL': $value = (!empty($input['model']))?$input['model']:'n/a'; break;
         case 'PRODUCTS_NAME': $value = $input['name']; break;
         case 'PRODUCTS_DESCRIPTION': $value = goodnl2br($input['desc']); break;
         case 'PRODUCTS_PRICE': $value = $input['price']; break;
         case 'PRODUCTS_IMAGE': $value = $imageFilename; break;
         case 'PRODUCTS_WEIGHT': $value = $input['weight']; break;
         case 'DATE_ADDED': $value = $date; break;
         case 'PRODUCTS_QUANTITY': $value = $input['quant']; break;
         case 'CATEGORIES_NAME_1': $value = $input['cat']; break;
         case 'TAX_CLASS_TITLE': $value = 'Taxable Goods'; break;
         case 'STATUS': $value = '1'; break;
         case 'EOREOR': $value = $val;break;
         default: $value = '';
      }
      $out[$val] = trim($value);
   }
   return $out;
}

function updateQueueFile($productArray) {   
   global $PKM;
   $cur = readQueueFile();
   if($cur === false) {$cur[] = explode("\t","v_products_model\tv_products_image\tv_products_name_1\tv_products_description_1\tv_products_url_1\tv_products_price\tv_products_weight\tv_date_avail\tv_date_added\tv_products_quantity\tv_manufacturers_name\tv_categories_name_1\tv_categories_name_2\tv_categories_name_3\tv_categories_name_4\tv_categories_name_5\tv_categories_name_6\tv_categories_name_7\tv_tax_class_title\tv_status\tEOREOR");}
   $cur[] = $productArray;
   saveQueueFile($cur);
}

function saveQueueFile($cur,$file='queue.csv') {
   if (!is_array($cur)) return false;
   $new = array();
   foreach ($cur as $row) $new[] = implode("\t",$row);
   $queueData = implode("\n",$new);      
   file_put_contents(ZENCART_PATH.'temp/'.$file, $queueData);
}

function doImageUpload() {
   $imgFullPath = DIR_FS_CATALOG_IMAGES;
   $imgThumbPath = DIR_FS_CATALOG_IMAGES.'thumb/';
   foreach ($_FILES as $key => $val) {
      if (is_uploaded_file($val['tmp_name'])) {
         $image = $val;
         $imgDeets = @getimagesize($image['tmp_name']);
         if (!in_array($imgDeets['mime'],array('image/jpeg'))) return false;
         $imageName = md5($image['name']).'.jpg';
         if (move_uploaded_file($image['tmp_name'],$imgFullPath.$imageName)) {
            global $up;
            $up->imageName = $imageName;
            $up->thumb(DIR_FS_CATALOG_IMAGES.$imageName,DIR_FS_CATALOG_IMAGES.'thumb/'.$imageName);
            $up->resize(DIR_FS_CATALOG_IMAGES.$imageName,DIR_FS_CATALOG_IMAGES.$imageName);
            @chmod(DIR_FS_CATALOG_IMAGES.$imageName,0777);
            @chmod(DIR_FS_CATALOG_IMAGES.'thumb/'.$imageName,0777);
            return $imageName;
         } // end if move_uploaded...
      } // end if is uploaded file
   }
   return false;
}

function deleteItem($id,$q=null){
   if ((int)$id == 0) return false;
   if (!is_array($q)) $q = readQueueFile();
   if (!empty($q[$id])) foreach ($q as $i=>$r) if ($i != $id) $o[] = $r;
   if (isset($o) && (is_array($o))) saveQueueFile($o);
}

function getUrl(){
  $ports = array('https' => 443, 'http' => 80);
  $prefix = (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off" ? 'http' : 'https');
  $url = $prefix;
  $url .= '://';
  $url .= $_SERVER['HTTP_HOST'];
  $url .= $_SERVER['SERVER_PORT'] != $ports[$prefix] ? ':' . $_SERVER['SERVER_PORT'] : '';
  $url .= $_SERVER['PHP_SELF'];
  $url .= (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != "" ? "?".$_SERVER['QUERY_STRING'] : "");
  return $url;
}

function reloadPage(){
   $url = explode('?',getUrl());
   header('Location: '.$url[0]);
}

function cleanInput($input){
    $_CLEAN = array();
    $errors = false;

    /*TODO: FIX!*/
    if (preg_match('/([a-z0-9 -\']+)+/i',$input['model'])) $_CLEAN['model'] = $input['model'];
    else $errors[] = 'Model Name is Required, And Must Be Alphanumeric And UNIQUE.';

    if (ctype_print($input['name'])) $_CLEAN['name'] = $input['name'];
    else $errors[] = 'Invalid Characters In Item Name.';

    $_CLEAN['price'] = floatval($input['price']);
    $_CLEAN['weight'] = floatval($input['weight']);
    $_CLEAN['quant'] = intval($input['quant']);
    $_CLEAN['cat'] = $input['cat'];
    $_CLEAN['desc'] = $input['desc'];

    if ($errors === false) return $_CLEAN;
    else return '<ul><li>'.implode('</li><li>',$errors).'</li></ul>';
}

function resetQueueFile($conf=false){
   if ($conf ===true) {
      @unlink(ZENCART_PATH.'temp/queue.csv');
      reloadPage();
   } elseif (($queue = readQueueFile()) !== false) {
      $queue = formatQueue($queue);
      echo '<div id="deleteConfirm" style="padding: 1em;text-align:center;">
            <h1 style="color:red;">DELETE (clear) Queue File?</h1><hr/>
            <a style="color:#000;background:#4F0;padding:5px;margin:1em;" href="eazyImport.php">NO!!!</a>
            <a style="color:#000;background:#F40;padding:5px;margin:1em;" href="eazyImport.php?reset=surewhynot">YES!!!</a></div>';
      die();
   }
}
?>